from server.algorithm import *
from server.pdStocks import PdStocks

from catchObj.Stocks import Stocks
import multiprocessing
from multiprocessing import Lock, Manager
import pymongo
import time

import pandas as pd
def ceshi():
    allStocks = Stocks.getAllStocks()
    pool = multiprocessing.Pool(processes=16)
    # allStocks = [['000008.SZ'],['000012.SZ']]
    # allStocks = [['000023.SZ']]
    t1 = time.time()
    for stock in allStocks:
        pool.apply_async(func=task,args=(stock[0],),callback=result)

# 运行: 689009.SH 成功： 213119 失败： 125460
    pool.close()
    pool.join()   #调用join之前，先调用close函数，否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
    t2 = time.time()-t1
    print("结束,耗时",t2)

def task(code):
    daily = PdStocks.getDaily(code)
    MACD(daily,'close',30)
    BOLL(daily)
    vv = daily['vol'].rolling(window=12).apply(getPoint2)
    daily['vv'] = vv
    kk = daily[(daily['vv']>0) & (daily['change']>0)]
    
    # print(daily[['M30','vv','close','date']][4839:4842])
    # print(len(kk))

    cc = 0
    ss = 0

    for index,_ in daily[(daily['vv']>0) & (daily['change']>0)].iterrows():
        jiange = index+3
        now_daily = daily.iloc[index]
        if len(daily)>=jiange:
            # #并且当前时间点中，靠近boll的下边线
            # if now_daily['median']>now_daily['close']:
            #     k = True
            # else:
            #     k = False

            #30日均线向上
            if daily.iloc[index-1]['M30']<now_daily['M30']:
                k=True
            else:
                k=False

            if k :
                if now_daily['close'] < daily.iloc[jiange]['close']:
                    # print(now_daily.date)
                    cc+=1
                else:
                    ss+=1
    # print("运行:",code,"成功：",cc,"失败：",ss)
    return (cc,ss,code)

def getPoint2(x):
    if x.iloc[-1]>x.mean()*1.5 and x.iloc[-1]<x.mean()*2:
        return 1
    else:
        return 0


c = 0
s = 0
def result(res):
    global c,s
    lock.acquire()
    c +=res[0]
    s +=res[1]
    lock.release()

    print("运行:",res[2],"成功：",res[0],"失败：",res[1],'总计：',c,s)

lock = Lock()

ceshi()